#!/usr/bin/env python3

from jirabl import *
import sys, time, os, re
from openpyxl import Workbook
from openpyxl.styles.borders import Border, Side
from openpyxl.utils import get_column_letter

FIVE_G_RELEASES=['5G19B','5G20A', '5G20B', '5G21A', '5G21B']
FIELD_LIST=['customfield_37381', # Feature ID
	        'key', 
            'summary', 
			'status', 
			'assignee',
			'customfield_38739', #System Spec End FB
            'customfield_38692', #FS2 EE
			'customfield_38690', # Competence Area
            'customfield_38737', #FS0 EE
			'customfield_31591' #Target End
            ]

ISSUE_INFO_LIST=['Feature ID','Key', 'Summary', 'FS Status and Dates', 'Target End' , 'FS2 EE (h)', 'Competence Area', 'FS0 EE (h)', 'Assignee', 'Status']


def parse_args():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-r", "--release", help="Specific planned release to be checked")
    args = parser.parse_args()

    if not args.release:
        print(parser.print_help())
        sys.exit(0)

    if args.release not in FIVE_G_RELEASES:
        print("Allowed Tasks: " + FIVE_G_RELEASES)
        sys.exit(0)
    return args

def enum_nidd_todo_items(jira, release):
    jql='issueFunction in portfolioChildrenOf(\'System = 5G AND "Target Releases" ~  "%s"  \') AND type = "Effort Estimation"   AND status not in  (DONE , OBSOLETE)'%release
	 #   issueFunction in portfolioChildrenOf('System = 5G AND "Planned System Release" = 5G20A ') AND type = "Effort Estimation"   AND status not in  (DONE , OBSOLETE)
    print(jql)
    item_list = jira.search_issues(jql_str=jql, maxResults=0, fields=FIELD_LIST)
    return item_list

def get_FS_Status(issue):
    jql='issueFunction in portfolioParentsOf("key=%s") AND issuetype in ("Customer Feature", "Internal Feature") '%str(issue.key)
    print(jql)
	#  'customfield_38705': 'FS Status and Dates',
    item_list = jira.search_issues(jql_str=jql, maxResults=1, fields=['customfield_38705'])
    if len(item_list):
        return get_fs_status(item_list[0])	
    else:
        return ""

def get_ETA_Target_End(issue):
    jql='issueFunction in portfolioParentsOf("key=%s") AND issuetype in ("Entity Technical Analysis") '%str(issue.key)
    print(jql)
	#  'customfield_38705': 'FS Status and Dates',
    item_list = jira.search_issues(jql_str=jql, maxResults=1, fields=['customfield_31591'])
    if len(item_list):
        return get_target_end(item_list[0])	
    else:
        return ""		
		
		
def get_EE_Target_End(issue):
    target_end = get_target_end(issue)
    if target_end:
        return target_end
    else:
        return get_ETA_Target_End(issue)			
		
		
		
def get_short_name(name):
    match = re.compile('(.*)\s\(.*\)').search(name)
    if match:
        return match.groups()[0]
    else:
        return name

def get_issue_info(issue):
    return {
	    'Feature ID': get_feature_id(issue),
        'Key':issue.key,
        'Link':issue.permalink(),
		# 'Issue Type':
        'Summary': get_summary(issue),
        'FS Status and Dates': get_FS_Status(issue),
        #'Target End': get_target_end(issue),
		'Target End' : get_EE_Target_End(issue),
        'FS2 EE (h)': get_fs2_ee(issue),
        'Competence Area' : get_competence_area(issue),
		#'Competence Area':   getCompetenceArea(issue),
        'FS0 EE (h)': get_fs0_ee(issue),
        'Assignee': getAssignee(issue),
		'Status': get_issue_status(issue)
    }

def add_sheet_header_wb(wb):
    for name in wb.sheetnames:
        add_sheet_header_ws(wb[name])

def add_sheet_header_ws(ws):
    # Set Column width
    ws.column_dimensions['A'].width = 12
    ws.column_dimensions['B'].width = 11
    ws.column_dimensions['C'].width = 70
    ws.column_dimensions['D'].width = 16
    ws.column_dimensions['E'].width = 17
    ws.column_dimensions['F'].width = 15
    ws.column_dimensions['G'].width = 26
    ws.column_dimensions['H'].width = 12
    ws.column_dimensions['I'].width = 25
    ws.column_dimensions['J'].width = 27

    # Insert Header
    ws.insert_rows(1)
    # Set border
    border = Border(left=Side(style='thin'), right=Side(style='thin'), top=Side(style='thin'),
                    bottom=Side(style='thin'))
    for i in range(1, 11, 1):
        ws.cell(1, i).border = border
        # ws.cell(1, i).style = "Headline 4"

    # Write Header
    n = 1
    for key in ISSUE_INFO_LIST:
        ws.cell(1, n).value = key
        n = n + 1

def keyIndex(keys, key):
    ret = 0
    try:
        ret = keys.index(key)
    except:
        ret = -1
    return ret

def find_empty_row(ws):
    n = 1
    while ws.cell(n,1).value:
        n = n + 1
    return n

def dump_issue(wb, sheet_name, issue_info):
    if sheet_name in wb.sheetnames:
        ws = wb[sheet_name]
    else:
        ws = wb.create_sheet(sheet_name)

    row = find_empty_row(ws)
    n = 1
    
    for key in ISSUE_INFO_LIST:
        print('\t', issue_info[key])
        if key == 'Key':
            ws.cell(row, 2).value = '=HYPERLINK("{}","{}")'.format(issue_info['Link'], issue_info['Key'])
            ws.cell(row, 2).style = "Hyperlink"
        else:
            ws.cell(row, n).value = issue_info[key]
        n = n + 1

def dumpe_to_excel(issue_list, file):
    print(file)
    if os.path.isfile(file):
        os.remove(file)

    wb = Workbook()
    wb.worksheets[0].title='All'

    keys=[]
    for issue in issue_list:
        if (keyIndex(keys, issue.key) < 0):
            keys.append(issue.key)
            issue_info = get_issue_info(issue)

            print("Dump item - %s"%get_summary(issue))
            dump_issue(wb, 'All', issue_info)

            #Dump issue to Domain page
            #if issue_info['Competence Area'] != '':
            #    dump_issue(wb, issue_info['Competence Area'], issue_info)

    add_sheet_header_wb(wb)
    wb.save(file_name)

if __name__ == '__main__':
    args = parse_args()

    jira = init_jira_connection()
    item_list = enum_nidd_todo_items(jira, args.release)
    file_name = 'FS2_EE_List_%s_%s.xlsx'%(args.release, time.strftime("%Y%m%d", time.localtime()))

    dumpe_to_excel(item_list, file_name)

